package com.sunday.ble.orlant.activity;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.sunday.ble.orlant.BaseApp;
import com.sunday.ble.orlant.R;
import com.sunday.ble.orlant.event.DoOption;
import com.sunday.ble.orlant.greendao.Device;
import com.sunday.ble.orlant.greendao.DeviceDao;
import com.sunday.common.event.EventBus;
import com.sunday.common.widgets.ClearEditText;
import com.sunday.common.widgets.taosty.Toasty;
import com.sunday.member.base.BaseActivity;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class UpdateNameActivity extends BaseActivity {

    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.etName)
    ClearEditText etName;
    @Bind(R.id.doUpdate)
    TextView doUpdate;

    private Device device;
    private DeviceDao deviceDao;
    private String name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_name);
        ButterKnife.bind(this);
        Bundle bundle = getIntent().getBundleExtra("device");
        if (bundle!=null){
            device = bundle.getParcelable("device");
        }
        deviceDao = BaseApp.getInstance().getDaoSession().getDeviceDao();
        initView();
    }

    private void initView(){
        showKeyboard();
        titleView.setText("修改名称");
        if (device!=null){
            etName.setText(device.getName());
            etName.setSelection(device.getName().length());
        }
    }

    private void showKeyboard(){
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(etName, 0);
    }

    @OnClick(R.id.doUpdate)
    public void onClick() {
        name = etName.getText().toString().trim();
        if (TextUtils.isEmpty(name)){
            Toasty.info(mContext,"名称不能为空").show();
            return;
        }
        updateName();
    }

    private void updateName(){
        device.setName(name);
        deviceDao.update(device);
        DoOption option = new DoOption();
        option.updateName = true;
        option.name = name;
        option.mac = device.getMac();
        EventBus.getDefault().post(option);
        Toasty.info(mContext,"修改成功").show();
        finish();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if(event.getKeyCode() == KeyEvent.KEYCODE_ENTER){
            name = etName.getText().toString().trim();
            if (TextUtils.isEmpty(name)){
                Toasty.info(mContext,"名称不能为空").show();
                return false;
            }
            closeInput(etName);
            updateName();
        }
        return super.dispatchKeyEvent(event);
    }
}
